package com.noah.bee.admin.Zookeeper;

import com.noah.bee.admin.web.pojo.ConfigInfo;
import com.noah.bee.core.exception.BeeException;
import com.noah.bee.core.support.PlaceholderChangeEvent;
import com.noah.bee.core.util.DecryptByDataBizUtil;
import com.noah.bee.core.util.InitPath2PathUtil;
import com.noah.bee.core.zookeeper.Environment;
import com.noah.bee.core.zookeeper.ZkPath;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 吴镇
 * @description:
 * @createdate 2017/1/3
 */
@Service
public class ZkClientService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZkClientService.class);

    private CuratorFramework client;

    @PostConstruct
    private void initZk(){
        this.client = CuratorFrameworkFactory.builder().connectString("10.21.40.55:2181").retryPolicy(new ExponentialBackoffRetry(2000, 3)).connectionTimeoutMs(3000).build(); // 构建zk客户端对象
        this.client.start();
    }

    /**
     * 获取节点数据
     * appName 应用节点名称
     * @return
     */
    public Map<String, String> getDataAndWatch(String appName) throws Exception {
        Map<String,String> map = null;
        String propertiesRootPath = ZkPath.forAppProperties(appName);
        List<String> childPaths = client.getChildren().forPath(propertiesRootPath);
        if (!(null == childPaths || childPaths.isEmpty())) {
            map = new HashMap<>();
            for (String path : childPaths) {
                String value = getData(completePath(propertiesRootPath,path)); // 拼接zk绝对路径并获取data
                if (null != value) {
                    if(path.endsWith("reinit")){
                        path = InitPath2PathUtil.initPath2Path(path);
                    }
                    map.put(ZkPath.getLastSubPath(path), value);
                }
            }
        }
        return map;
    }

    /**
     * 获取单条配置信息
     * @param appName
     * @param configName
     * @return
     */
    public ConfigInfo getConfig(String appName, String configName){
        String value = getData(completePath(ZkPath.forAppProperties(appName),configName));
        ConfigInfo configInfo = null;
        if(null != value){
            configInfo = new ConfigInfo(configName,value);
        }
        return configInfo;
    }

    public String createNodeAndData(String appName, String propertyName, String value) throws Exception {
        String propertiesRootPath = ZkPath.forAppProperties(appName);
        Stat stat = client.checkExists().forPath(completePath(propertiesRootPath,propertyName));
        String path = client.create().creatingParentsIfNeeded().forPath(completePath(propertiesRootPath,propertyName),value.getBytes());
        return path;
    }

    public void updateConfig(String appName, String propertyName, String value) throws Exception {
        String propertiesRootPath = ZkPath.forAppProperties(appName);
        Stat stat = client.setData().forPath(completePath(propertiesRootPath,propertyName),value.getBytes());
    }

    public String deleteDataAndNode(String appName, String propertyName) throws Exception {
        String propertiesRootPath = ZkPath.forAppProperties(appName);
        Stat stat = client.checkExists().forPath(completePath(propertiesRootPath,propertyName));
        Void forPath = client.delete().deletingChildrenIfNeeded().forPath(completePath(propertiesRootPath,propertyName));
        return "";
    }

    private String getData(String path){
        String value = null;
        try {
            byte[] bytes = client.getData().forPath(path);
            if (null != bytes) {
                value = new String(bytes, "UTF-8");
            }
        } catch (KeeperException.NoNodeException e) {
            LOGGER.warn("当前节点：" + path + "不存在:" + e.getMessage());
        } catch (Exception e) {
            LOGGER.error("获取节点：" + path + "出错:" + e.getMessage());
            throw new BeeException("获取节点：" + path + "出错:" + e.getMessage());
        }
        return value;
    }

    /**
     * 获取 property name所指向的zk 节点的完整路径
     * 将properties name作为节点名称，属性值作为data存放
     * @param propertyName 属性名称,如: "user.name"
     * @return path, 如: "/apps/jobapp/properties/user.name"
     */
    private String completePath(String propertiesRootPath, String propertyName) {
        return propertiesRootPath + ((propertyName.startsWith("/")) ? "" : "/") + propertyName;
    }

    /**
     * 添加监听
     * @param path 监听节点
     *//*
    private void addWatch(String path) {
        final PathChildrenCache childCache = new PathChildrenCache(client, path, true);
        try {
            childCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
            childCache.getListenable().addListener(new PathChildrenCacheListener() {
                // 回调事件
                @Override
                public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                    String propertyNodeName = (null == event.getData()) ? null : ZkPath.getLastSubPath(event.getData().getPath());
                    switch (event.getType()) {
                        // 判断通知类型
                        // 子节点变更或者新增
                        case CHILD_ADDED:
                        case CHILD_UPDATED:
                            String value = (null == event.getData()) ? "" : new String(event.getData().getData());
                            if (null != propertyNodeName && propertyNodeName.length() > 0) {

                            }
                            break;
                        case CHILD_REMOVED:
                            if (null != propertyNodeName && propertyNodeName.length() > 0) {

                            }
                            break;
                        case CONNECTION_RECONNECTED: // 重新连接事件通知
                            childCache.rebuild();
                            LOGGER.info("rebuild listener after reconnected from zookeeper(" + Environment.getZkServer() + ")");
                            break;
                        case CONNECTION_SUSPENDED: // 连接暂停
                        case CONNECTION_LOST: // 连接丢失
                            LOGGER.warn("disconnected from zookeeper server(" + Environment.getZkServer() + ")");
                            break;
                        default:
                            break;
                    }
                }
            }, Executors.newFixedThreadPool(3));
        } catch (Exception e) {
            throw new BeeException("监听zk节点失败：" + e.getMessage());
        }
    }*/

}
